package com.kvest.testtask.network;

import java.io.IOException;
import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

import com.kvest.testtask.datamodel.Site;

public class SitesXMLParser 
{
	private static final String SITES_TAG = "sites";
	private static final String SITE_TAG = "site";
	private static final String COUNTRY_NAME_TAG = "county_name";
	private static final String DESCRIPTION_TAG = "description";
	private static final String FEAT_CLASS_TAG = "feat_class";
	private static final String FEATURE_ID_TAG = "feature_id";
	private static final String FIPS_CLASS_TAG = "fips_class";
	private static final String FIPS_COUNTRY_CD_TAG = "fips_county_cd";
	private static final String FULL_COUNTRY_NAME_TAG = "full_county_name";
	private static final String LINK_TITLE_TAG = "link_title";
	private static final String URL_TAG = "url";
	private static final String NAME_TAG = "name";
	private static final String PRIMARY_LATITUDE_TAG = "primary_latitude";
	private static final String PRIMARY_LONGITUDE_TAG = "primary_longitude";
	private static final String STATE_ABBREVIATION_TAG = "state_abbreviation";
	private static final String STATE_NAME_TAG = "state_name";
	private static final String COUNT_PROPERTY = "count";
	
	public SitesXMLParser()
	{
		
	}
	
	public static Site[] parseSites(String xml)
	{
		XmlPullParser parser = Xml.newPullParser();
		try
		{
			parser.setInput(new StringReader(xml));
			
			Site[] result = null;
			
			if (parser.next() == XmlPullParser.START_TAG)
			{
				parser.require(XmlPullParser.START_TAG, "", SITES_TAG);
				
				String countStr = parser.getAttributeValue("", COUNT_PROPERTY);
				result = new Site[Integer.parseInt(countStr)];
				
				String tagName;
				int i = 0;
				while (parser.next() != XmlPullParser.END_TAG) 
				{
					if (parser.getEventType() != XmlPullParser.START_TAG) 
					{
			            continue;
			        }
					
					parser.require(XmlPullParser.START_TAG, "", SITE_TAG);
					
					//Create and fill Site object
					result[i] = new Site();
					while (parser.next() != XmlPullParser.END_TAG)
					{
						tagName = parser.getName();
						
						if (tagName.equals(COUNTRY_NAME_TAG))
						{
							result[i].setCountyName(getText(parser));
						}
						else if (tagName.equals(DESCRIPTION_TAG))
						{
							result[i].setDescription(getText(parser));
						}
						else if (tagName.equals(FEAT_CLASS_TAG))
						{
							result[i].setFeatClass(getText(parser));
						}
						else if (tagName.equals(FEATURE_ID_TAG))
						{
							result[i].setFeatureId(getInt(parser));
						}
						else if (tagName.equals(FIPS_CLASS_TAG))
						{
							result[i].setFipsClass(getText(parser));
						}
						else if (tagName.equals(FIPS_COUNTRY_CD_TAG))
						{
							result[i].setFipsCountyCd(getInt(parser));
						}
						else if (tagName.equals(FULL_COUNTRY_NAME_TAG))
						{
							result[i].setFullCountyName(getText(parser));
						}
						else if (tagName.equals(LINK_TITLE_TAG))
						{
							result[i].setLinkTitle(getText(parser));
						}
						else if (tagName.equals(URL_TAG))
						{
							result[i].setUrl(getText(parser));
						}
						else if (tagName.equals(NAME_TAG))
						{
							result[i].setName(getText(parser));
						}
						else if (tagName.equals(PRIMARY_LATITUDE_TAG))
						{
							result[i].setPrimaryLatitude(getFloat(parser));
						}
						else if (tagName.equals(PRIMARY_LONGITUDE_TAG))
						{
							result[i].setPrimaryLongitude(getFloat(parser));
						}
						else if (tagName.equals(STATE_ABBREVIATION_TAG))
						{
							result[i].setStateAbbreviation(getText(parser));
						}
						else if (tagName.equals(STATE_NAME_TAG))
						{
							result[i].setStateName(getText(parser));
						}
						else
						{
							skip(parser);
						}
					}
					
					++i;
				}
			}
			
			return result;
		}
		catch(Exception ex)
		{
			return null;
		}
	}
	
	private static int getInt(XmlPullParser parser) throws XmlPullParserException, IOException 
	{
		//Go to Text
		parser.next();
		
		//Get int as text
		String resultStr = parser.getText();
		
		int result;
		//convert
		try
		{
			result = Integer.parseInt(resultStr);
		}
		catch(Exception ex)
		{
			result = 0;
		}
		
		//Go to next tag
		if (parser.getEventType() != XmlPullParser.END_TAG)
		{
			parser.next();
		}
		
		return result;
	}
	
	private static float getFloat(XmlPullParser parser) throws XmlPullParserException, IOException 
	{
		//Go to Text
		parser.next();
		
		//Get float as text
		String resultStr = parser.getText();
		
		float result;
		//convert
		try
		{
			result = Float.parseFloat(resultStr);
		}
		catch(Exception ex)
		{
			result = 0;
		}
		
		//Go to next tag
		if (parser.getEventType() != XmlPullParser.END_TAG)
		{
			parser.next();
		}
		
		return result;
	}
	
	private static String getText(XmlPullParser parser) throws XmlPullParserException, IOException 
	{
		//Go to Text
		parser.next();
		
		//Get text
		String result = parser.getText();
		
		//if text is null - set to empty string
		if (result == null)
		{
			result = "";
		}
		
		//Go to next tag
		if (parser.getEventType() != XmlPullParser.END_TAG)
		{
			parser.next();
		}
		
		return result;
	}
	
	
	private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException 
	{
	    if (parser.getEventType() != XmlPullParser.START_TAG) 
	    {
	        throw new IllegalStateException();
	    }
	    int depth = 1;
	    while (depth != 0) 
	    {
	        switch (parser.next()) 
	        {
		        case XmlPullParser.END_TAG:
		            depth--;
		            break;
		        case XmlPullParser.START_TAG:
		            depth++;
		            break;
	        }
	    }
	}
}
